package com.zk.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;


/**
 * Word文档工具类
 */
@Slf4j
public class FreemarkerWordUtil {

    /**
     * 生成word
     *
     * @param dataMap          数据
     * @param templateFileName 模板名
     * @param outputDocPath    word保存路径
     */
    public static void createWord(
            Map<String, Object> dataMap, String templateFileName, String outputDocPath) {
        log.info(
                "======Freemarker - createWord: 模板名: {} , word保存路径: {}", templateFileName, outputDocPath);
        try (FileOutputStream fos = new FileOutputStream(new File(outputDocPath));
             OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
             Writer out = new BufferedWriter(osw)) {

            Configuration configuration =
                    new Configuration(freemarker.template.Configuration.VERSION_2_3_25);
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassicCompatible(true);
            configuration.setTemplateLoader(
                    new ClassTemplateLoader(FreemarkerWordUtil.class.getClassLoader(), "templates"));
            // 获取模板文件
            Template t = configuration.getTemplate(templateFileName, "UTF-8");
            // 将填充数据填入模板文件并输出到目标文件
            t.process(dataMap, out);
        } catch (Exception e) {
            log.error("======Freemarker - createWord异常：", e);
        }
    }
}
